/*
 * =====================================================================================
 *       Filename:  chandir_cmd.c
 *    Description:  
 *        Version:  2.0
 *        Created:  2017.06.03 17:51
 *         Author:  fujiajun (fjj), fujiajun@renren1.com
 *        Company:  HOOLINKS
 * =====================================================================================
 */

#include "xshell.h"

void chandir_cmd(char* param[PARAMNUM]){
    struct passwd* pwd;
    char* cd_path = NULL;

    // 获取用户信息，同时可以获得该用户home目录的路径
    pwd = getpwuid(getuid());

    // 对参数进行分析
    if(param[0] == NULL) {
        // 若无参数，跳到home目录  
        cd_path = malloc(strlen(pwd->pw_dir));
        strcpy(cd_path, pwd->pw_dir);
        
    } else if(param[0][0] == '~') {
        // 跳到以～作前缀的路径
        cd_path = malloc(strlen(pwd->pw_dir) + strlen(param[0]));
        if(cd_path == NULL) {
            printf("chandir：获取内存失败\n");
        } else {
            strcpy(cd_path, pwd->pw_dir);
            strncpy(cd_path + strlen(pwd->pw_dir), param[1]+1, strlen(param[1]));
        }

    } else {

        // 正常路径处理
        cd_path = malloc(strlen(param[0] + 1));
        if(cd_path == NULL) {
            printf("chandir：获取内存失败\n");
        } else {
            strcpy(cd_path, param[0]);
        }      
    }

    // 更改当前工作目录，失败则打印错误信息
    if(chdir(cd_path) != 0){
        printf("chandir %s：更改工作目录失败\n%s\n", cd_path, strerror(errno));
    }
        
    // 释放空间
    free(cd_path);
}